import { create as defineStore } from "zustand";
import { persist } from "zustand/middleware";
import {
  login,
  LoginDto,
  register,
  RegisterDto,
  registerCaptcha,
  CaptchaDto,
  updatePasswordCaptcha,
  updatePassword,
  UpdatePasswordDto,
  updateUserInfo,
  UpdateUserDto,
  getUserInfo,
} from "../apis";
import { message } from "antd";

export interface IUser {
  id: number;
  username: string;
  nickName: string;
  email: string;
  avatar: string;
  createTime: string;
}

export interface AuthUser {
  token: string;
  user: IUser;
}

interface State {
  userInfo: IUser | null;
}

interface Action {
  login: (values: LoginDto) => Promise<[boolean, AuthUser]>;
  register: (values: RegisterDto) => Promise<[boolean, IUser]>;
  sendRegisterCaptcha: (email: CaptchaDto) => Promise<[boolean, string]>;
  sendUpdatePasswordCaptcha: (email: CaptchaDto) => Promise<[boolean, string]>;
  updatePassword: (values: UpdatePasswordDto) => Promise<[boolean, string]>;
  updateUserInfo: (userInfo: UpdateUserDto) => Promise<[boolean, string]>;
  getUserInfo: () => Promise<[boolean, IUser]>;
  logout: () => Promise<[boolean, string]>;
}

export const useUserStore = defineStore<State & Action>()(
  persist(
    (set) => ({
      userInfo: null,
      login: async (values) => {
        const res = await login(values);
        const [success, data] = res;
        if (success) {
          const { token, user } = data;
          localStorage.setItem("token", token);
          localStorage.setItem("userInfo", JSON.stringify(user));
          set({ userInfo: user });
        }
        return res;
      },
      register: async (values) => {
        const res = await register(values);
        const [success] = res;
        if (success) {
          message.success("注册成功");
          setTimeout(() => {
            window.location.href = "/login";
          }, 1000);
        }
        return res;
      },
      sendRegisterCaptcha: async (values: CaptchaDto) => {
        return await registerCaptcha(values);
      },
      sendUpdatePasswordCaptcha: async (values: CaptchaDto) => {
        return await updatePasswordCaptcha(values);
      },
      updatePassword: async (values: UpdatePasswordDto) => {
        const res = await updatePassword(values);
        const [success] = res;
        if (success) {
          message.success("密码修改成功");
          setTimeout(() => {
            window.location.href = "/login";
          }, 1000);
        }
        return res;
      },
      updateUserInfo: async (partUserInfo: UpdateUserDto) => {
        const res = await updateUserInfo(partUserInfo);
        const [success] = res;
        if (success) {
          // 更新本地存储的用户信息
          // localStorage.setItem("userInfo", JSON.stringify(userInfo));
          // 更新状态
          set({
            userInfo: Object.assign(
              {},
              useUserStore.getState().userInfo,
              partUserInfo
            ),
          });
        }
        return res;
      },
      getUserInfo: async () => {
        const res = await getUserInfo();
        const [success, data] = res;
        if (success) {
          // 更新本地存储的用户信息
          // localStorage.setItem("userInfo", JSON.stringify(data));
          // 更新状态
          set({ userInfo: data });
        }
        return res;
      },
      logout: async () => {
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        set({ userInfo: null });
        return [true, "退出登录成功"];
      },
    }),
    {
      name: "user",
    }
  )
);
